package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.zhijian.medical.annotation.ValidateMeetingKeyCode;
import com.zhijian.medical.config.Constants;
import com.zhijian.medical.entity.dto.MeetingHstKeyCodeDto;
import com.zhijian.medical.entity.dto.MeetingHstRoomsListDto;
import com.zhijian.medical.entity.vo.request.MeetingHstRoomsListSearchVo;
import com.zhijian.medical.entity.vo.response.MeetingHstRoomsListVo;
import com.zhijian.medical.service.CacheService;
import com.zhijian.medical.service.MeetingService;
import com.zhijian.medical.util.EncryptUtil;
import com.zhijian.medical.util.JsonUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author HCG
 * @version 1.0
 * @date 2023-09-14
 */
@Service
@Slf4j
public class MeetingServiceImpl implements MeetingService {

    /**
     * 超时时间，单位毫秒
     */
    private static final int TIME_OUT = 1000 * 20;

    /**
     * 好视通账号
     */
    @Value("${meeting.hst.username}")
    @Getter
    @Setter
    private String meetingHstUsername;

    /**
     * 好视通密码
     */
    @Value("${meeting.hst.password}")
    @Getter
    @Setter
    private String meetingHstPassword;

    @Autowired
    private CacheService cacheService;

    /**
     * 获取key-code的url
     */
    private static final String KEY_CODE_URL = "https://meetingapi.hst.com/companies/key-code";

    /**
     * 多条件查询会议室列表的url
     */
    private static final String ROOMS_LIST_URL = "https://meetingapi.hst.com/companies/rooms/list";

    @Override
    public MeetingHstKeyCodeDto.ResponseDto selectKeyCode(String body) {
        try {
            //链式构建请求
            HttpResponse httpResponse = HttpRequest.post(KEY_CODE_URL)
                    .header("Content-Type", "application/json")
                    //超时，毫秒
                    .timeout(TIME_OUT)
                    .body(body)
                    .execute();
            String responseBody = httpResponse.body();
            try {
                return JsonUtil.toBean(responseBody, MeetingHstKeyCodeDto.ResponseDto.class);
            } catch (Exception e) {
                log.error("the response body of device subscribeMessage is not legal...", e.getMessage());
                e.printStackTrace();
                return null;
            }
        } catch (Exception e) {
            log.error("the request of device subscribeMessage.send cause error...", e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public MeetingHstKeyCodeDto.ResponseDto selectKeyCode(MeetingHstKeyCodeDto.RequestDto requestDto) {
        return selectKeyCode(JsonUtil.toString(requestDto));
    }

    @Override
    public String getKeyCode() {
        MeetingHstKeyCodeDto.ResponseDto responseDto = this.selectKeyCode(MeetingHstKeyCodeDto.RequestDto.builder()
                .rootuname(meetingHstUsername)
                .pwd_md5(EncryptUtil.md5(meetingHstPassword))
                .publicKey("3025495AEE146DA3864AB81BAAF79A3E")
                .build());
        if (Objects.nonNull(responseDto) && "0000".equals(responseDto.getCode())) {
            return responseDto.getResult();
        }
        return null;
    }

    @Override
    public void storeKeyCode() {
        String keyCode = this.getKeyCode();
        if (StringUtils.isNotBlank(keyCode)) {
            cacheService.setex(Constants.Redis.MEETING_KEY_CODE, 60 * 60 * 24, keyCode);
            log.info("set the keycode in cache,{}", keyCode);
        }
    }

    @ValidateMeetingKeyCode
    @Override
    public MeetingHstRoomsListDto.ResponseDto selectRoomsList(String body) {
        try {
            //链式构建请求
            HttpResponse httpResponse = HttpRequest.post(ROOMS_LIST_URL)
                    .header("Content-Type", "application/json")
                    .header("Key-Code", cacheService.get(Constants.Redis.MEETING_KEY_CODE))
                    //超时，毫秒
                    .timeout(TIME_OUT)
                    .body(body)
                    .execute();
            String responseBody = httpResponse.body();
            try {
                return JsonUtil.toBean(responseBody, MeetingHstRoomsListDto.ResponseDto.class);
            } catch (Exception e) {
                log.error("the response body of device subscribeMessage is not legal...", e.getMessage());
                e.printStackTrace();
                return null;
            }
        } catch (Exception e) {
            log.error("the request of device subscribeMessage.send cause error...", e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public MeetingHstRoomsListDto.ResponseDto selectRoomsList(MeetingHstRoomsListDto.RequestDto requestDto) {
        return selectRoomsList(JsonUtil.toString(requestDto));
    }

    @Override
    public List<MeetingHstRoomsListVo> selectMeetingHstRoomsListVo(MeetingHstRoomsListSearchVo meetingHstRoomsListSearchVo) {
        MeetingHstRoomsListDto.RequestDto requestDto = new MeetingHstRoomsListDto.RequestDto();
        BeanUtils.copyProperties(meetingHstRoomsListSearchVo, requestDto);
        MeetingHstRoomsListDto.ResponseDto responseDto = this.selectRoomsList(requestDto);
        if (Objects.nonNull(responseDto) && "0000".equals(responseDto.getCode())) {
            List<MeetingHstRoomsListDto.ResponseDto.DataDto> responseDtoResult = responseDto.getResult();
            if (CollectionUtil.isNotEmpty(responseDtoResult)) {
                return responseDtoResult.stream().map(r -> {
                    MeetingHstRoomsListVo meetingHstRoomsListVo = new MeetingHstRoomsListVo();
                    BeanUtils.copyProperties(r, meetingHstRoomsListVo);
                    return meetingHstRoomsListVo;
                }).collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }

}
